<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.wxAccountId" placeholder="请选择公众号" clearable class="filter-item" style="width: 200px;margin-right: 20px">
        <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <!--<el-input :placeholder="'请输入' + tempDesc.nicknameStr" v-model="listQuery.nicknameStr" style="width: 200px;margin-right: 20px" class="filter-item"-->
                <!--@keyup.enter.native="handleFilter"/>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <!--<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"-->
                 <!--@click="handleCreate">{{ $t('table.add') }}-->
      <!--</el-button>-->
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;">
      <el-table-column :label="tempDesc.wxAccountName">
        <template slot-scope="scope">
          <span>{{ scope.row.wxAccountName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.nicknameStr" width="120px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.nicknameStr }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.headimgUrl"  width="120px" show-overflow-tooltip>
        <template slot-scope="scope">

          <el-popover
            placement="top-start"
            trigger="hover">
            <span>
              <img :src="scope.row.headimgUrl" alt="" style="width: 200px;height: 200px">
            </span>
            <span slot="reference">
              <img :src="scope.row.headimgUrl" alt="" style="width: 50px;height: 50px">
            </span>
          </el-popover>

          <!--<span>-->
            <!--<img :src="scope.row.headimgUrl" alt="" style="width: 50px;height: 50px">-->
          <!--</span>-->
        </template>
      </el-table-column>

      <el-table-column :label="tempDesc.msgType" :formatter="formatMsgType">
        <!--<template slot-scope="scope">-->
          <!--<span>{{ scope.row.msgType }}</span>-->
        <!--</template>-->
      </el-table-column>
      <el-table-column :label="tempDesc.content">
        <template slot-scope="scope">
          <span>{{ scope.row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.picPath">
        <template slot-scope="scope">
          <template v-if="!!scope.row.picPath">
            <el-popover
              placement="top-start"
              trigger="hover">
              <span>
                <img :src="_getShowImageURL(scope.row.picPath)" alt="" style="width: 200px;height: 200px">
              </span>
              <span slot="reference">
                <img :src="_getShowImageURL(scope.row.picPath)" alt="" style="width: 50px;height: 50px">
              </span>
            </el-popover>
          </template>
          <template v-else>
          </template>
          <!--<span>-->
          <!--<img :src="scope.row.picUrl" alt="" style="width: 50px;height: 50px">-->
          <!--</span>-->
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.resContent" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.resContent }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.isRes">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isRes == 1 ? 'success' : 'danger'" hit>{{ scope.row.isRes == 1 ? '已回复' : '未回复' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column :label="tempDesc.createTime" width="160px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.updateTime" width="160px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" width="200px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
          <el-button type="primary" size="mini" style="width: 80px;margin-left: 10px" @click="handleUpdate(scope.row)">快捷回复</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>

    <el-dialog title="快捷回复" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px"
               style="width: 400px; margin-left:50px;">

        <el-form-item :label="tempDesc.resContent" prop="resContent">
          <el-input type="textarea" :rows="7" maxlength="100" v-model="temp.resContent" :placeholder="'请输入' + tempDesc.resContent"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {fetchList, createRow, updateRow, deleteRow, updateResContent} from '@/api/wx-fans-msg'
  import {fetchAllAccount} from '@/api/wx-account'
  import waves from '@/directive/waves' // Waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  import { getShowImageURL } from '@/utils'

  //常量title
  const tempDesc = {
    "id": "",
    "openid": "OpenId",
    "headimgUrl": "头像的地址",
    "wxAccountId": "公众号名称",
    "msgType": "消息类型",
    "content": "粉丝发送内容",
    "resContent": "回复内容",
    "isRes": "是否已回复",
    "mediaId": "素材ID",
    "picUrl": "图片地址",
    "picPath": "粉丝发送图片",
    "createTime": "创建时间",
    "updateTime": "更新时间",
    "nickname": "昵称",
    "nicknameStr": "昵称",
    "wxAccountName":"公众号名称"
  };
  export default {
    //name: 'ComplexTable',
    components: {Pagination},
    directives: {waves},
    filters: {},
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          wxAccountId:""
        },
        showReviewer: false,
        temp: {
          "id": "",
          "openid": "",
          "headimgUrl": "",
          "wxAccountId": "",
          "msgType": "",
          "content": "",
          "resContent": "",
          "isRes": "",
          "mediaId": "",
          "picUrl": "",
          "picPath": "",
          "createTime": "",
          "updateTime": "",
          "nickname": "",
          "nicknameStr": "",
          "wxAccountName":""
        },
        tempDesc: tempDesc,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '增加'
        },
        rules: {
          resContent: [{required: true, message: '请输入' + tempDesc.resContent, trigger: 'blur'}],
        },
        accountListOptions:[

        ]

      }
    },
    created() {
      this.getList();
      this.getAccountList();
    },
    methods: {
      getList() {
        this.listLoading = true
        this.getAccountList();
        fetchList(this.listQuery).then(response => {
          this.list = response.data.list
          this.total = response.data.total

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetTemp() {
        this.temp = {
          "id": "",
          "openid": "",
          "headimgUrl": "",
          "wxAccountId": "",
          "msgType": "",
          "content": "",
          "resContent": "",
          "isRes": "",
          "mediaId": "",
          "picUrl": "",
          "picPath": "",
          "createTime": "",
          "updateTime": "",
          "nickname": "",
          "nicknameStr": "",
          "wxAccountName":""
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            createRow(this.temp).then(() => {
              this.getList();
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj

        //回复内容置为空
        this.temp.resContent = "";

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            //const tempData = Object.assign({}, this.temp);
            const tempData = {id:this.temp.id,resContent:this.temp.resContent,isRes:"1"};
            updateResContent(tempData).then(() => {
              this.getList();
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            var params = {"id": row.id};
            deleteRow(params).then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              this.getList();
            });
          });
      },
      getAccountList(){
        fetchAllAccount().then(response => {
          this.accountListOptions = [];
          for(var i=0;i<response.data.length;i++){
            this.accountListOptions.push({"key":response.data[i].id + '',"display_name":response.data[i].name});
          }
        });
      },
      syncAccountFans(){
        if(this.accountSelected == ''){
          this.$message({ message: '请选择公众号', type: 'warning' });
          return false;
        }
        this.$confirm('确认需要同步粉丝信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var params = {"id":this.accountSelected};
          syncAccountFans(params).then(response => {
            this.getList();
            this.$notify({
              title: '成功',
              message: '同步粉丝成功，请稍后刷新数据查看',
              type: 'success',
              duration: 2000
            })
          });
        });
      },
      _getShowImageURL(filepath){
          return getShowImageURL(filepath);
      },
      formatMsgType(row,column){
        switch (row.msgType) {
          case 'text':
            return "文本";
            break;
          case 'image':
            return "图片";
            break;
          default :
            return "";
            break;
        }
      }
    }
  }
</script>
